/**   
 * @Title: ParticleApplet.java 
 * @Package com.forever.thread.gui 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author leo   
 * @date 2014-9-16 上午11:31:27
 */
package com.forever.thread.gui;

import java.applet.Applet;

/**
 * @ClassName: ParticleApplet
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author leo
 * @date 2014-9-16 上午11:31:27
 * 
 */
@SuppressWarnings("serial")
public class ParticleApplet extends Applet {

	protected Thread[] threads = null;
	protected final ParticleCanvs canvs = new ParticleCanvs(100);

	public void init() {
		add(canvs);
	}

	protected Thread makeThread(final Particle particle) {
		Runnable runloop = new Runnable() {

			@Override
			public void run() {
				try {
					for (;;) {
						particle.move();
						canvs.repaint();
						Thread.sleep(1000);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		return new Thread(runloop);
	}

	public synchronized void start() {
		int n = 10;
		if (threads == null) {
			Particle[] particles = new Particle[n];
			for (int i = 0; i < n; i++) {
				particles[i] = new Particle(50, 50);
				canvs.setParticles(particles);

				threads = new Thread[n];
				for (int j = 0; j < n; i++) {
					threads[j] = makeThread(particles[j]);
					threads[j].start();

				}
			}
		}
	}

	public synchronized void stop() {
		if (null != threads) {
			for (int i = 0; i < threads.length; i++) {
				threads[i].interrupt();
				threads = null;

			}
		}
	}

	public static void main(String[] args) {
		ParticleApplet applet = new ParticleApplet();
		applet.start();
	}
}
